/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.mlbs.session.generated;

import com.mlbs.entity.Device;
import com.mlbs.entity.Devicelocation;
import com.mlbs.entity.Usertable;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author mckd87
 */
@PersistenceContext(name="mlbs-ejbPU", unitName="mlbs-ejbPU")
@Stateless
public class DevicelocationFacade implements DevicelocationFacadeRemote {
    @EJB
    private DeviceFacadeRemote deviceFacade;
    @PersistenceContext(unitName="mlbs-ejbPU")
    private EntityManager em;

    public void create(Devicelocation devicelocation) {
        em.persist(devicelocation);
    }

    public void edit(Devicelocation devicelocation) {
        em.merge(devicelocation);
    }

    public void remove(Devicelocation devicelocation) {
        em.remove(em.merge(devicelocation));
    }

    public Devicelocation find(Object id) {
        return em.find(com.mlbs.entity.Devicelocation.class, id);
    }

    public List<Devicelocation> findAll() {
        return em.createQuery("select object(o) from Devicelocation as o").getResultList();
    }

    public void setDeviceLocation(String cityName, String stateName, String streetAddress, String latitude, String longitude, String imei) {
       Device device = deviceFacade.find(imei);
        Usertable user = device.getUserid();
        Devicelocation loc = device.getDevicelocation();
        if(loc == null){
            loc = new Devicelocation(imei);
            loc.setCity(cityName);
            //loc.setDevice(device);
            loc.setLastUpdate(new Date(System.currentTimeMillis()));
            loc.setLat(new Float(latitude));
            loc.setLongitude(new Float(longitude));
            loc.setStreet(streetAddress);
            loc.setState(stateName);
            loc.setUserid(user);
            create(loc);
        }else{
            loc.setCity(cityName);
            loc.setDevice(device);
            loc.setLastUpdate(new Date(System.currentTimeMillis()));
            if(latitude!=null && latitude.length() > 0){
                loc.setLat(new Float(latitude));
            }
            if(longitude != null && longitude.length() > 0){
                loc.setLongitude(new Float(longitude));
            }
            loc.setStreet(streetAddress);
            loc.setState(stateName);
            edit(loc);
        }
    }

}
